Java syntax
part 37/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Lambda's parameters types do not have to be fully specified and can be inferred from the interface it implements. Lambda's body can be written without a body block and a return statement if it is only an expression. Also, for those interfaces which only have a single parameter in the method, round brackets can be omitted.cite-ref-8[8]
// Same call as above, but with fully specified types and a body block
runCalculation((int number, int otherNumber) -> {
return number + otherNumber;
});
// A functional interface with a method which has only a single parameter
interface StringExtender {
String extendString(String input);
}
// Initializing a variable of this type by using a lambda
StringExtender extender = input -> input + " Extended";
Method references
It is not necessary to use lambdas when there already is a named method compatible with the interface. This method can be passed instead of a lambda using a method reference. There are several types of method references:
| Reference type | Example | Equivalent lambda |
|---|---|---|
| Static | Integer::sum | (number, otherNumber) -> number + otherNumber |
| Bound | "LongString"::substring | index -> "LongString".substring(index) |
| Unbound | String::isEmpty | string -> string.isEmpty() |
| Class constructor | ArrayList<String>::new | capacity -> new ArrayList<String>(capacity) |
| Array constructor | String[]::new | size -> new String[size] |
The code above which calls runCalculation could be replaced with the following using the method references:
runCalculation(Integer::sum);
Inheritance